package com.ykq.service.impl;

import com.ykq.dao.MenuDao;
import com.ykq.entity.Menu;
import com.ykq.service.MenuService;
import com.ykq.util.CommonResult;
import com.ykq.util.JwtUtils;
import com.ykq.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: springboot-vue
 * @description:
 * @author: 闫克起2
 * @create: 2021-12-31 11:10
 **/
@Service(value = "menuService")
public class MenuServiceImpl  implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Override
    public CommonResult findLeftMenu() {
        //1.根据用户id查询该用户具有的左侧菜单 TODO 以后登录后一定能获取
        //从请求头中获取token的值。 解析该token可以获取roleid.
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        int roleid=Integer.parseInt( JwtUtils.getClaimByName(token,"roleId").asString());

        //2. 查询当前用户的菜单
        List<Menu> list=menuDao.selectLeftMenu(roleid);

        //3. 菜单分层
        //(1)一级菜单
        List<Menu> first=new ArrayList<>();
        for (Menu m:list){
            if(m.getMpid()==0){
                 first.add(m);
            }
        }
        //(2)调用查询子菜单
        for(Menu f:first){
              f.setChildren(findChildren(list,f.getMid()));
        }

        return new CommonResult(2000,"查询成功",first);
    }

    public List<Menu> findChildren(List<Menu> menus,int pid){
            List<Menu> children=new ArrayList<>();
            for (Menu menu:menus) {
                   if(menu.getMpid()==pid){
                        children.add(menu);
                   }
            }
            for (Menu child:children){
                  child.setChildren(findChildren(menus,child.getMid()));
            }
            return children;
    }
}











